<template>
  <!-- 筛选区 -->
  <div class="sub-filter">
    <!-- 根据二级分类确定筛选条件 -->

    <!-- 品牌是固定的 -->
    <div class="item">
      <div class="head">品牌：</div>
      <div class="body">
        <a
          @click="selectBrand(brand)"
          :class="{ active: brand.selected }"
          href="javascript:;"
          v-for="brand in subCategoryData.brands"
          :key="brand.id"
          >{{ brand.name }}</a
        >
      </div>
    </div>

    <!--其它筛选条件-->
    <div
      class="item"
      v-for="prd in subCategoryData.saleProperties"
      :key="prd.id"
    >
      <div class="head">{{ prd.name }}</div>
      <div class="body">
        <a
          @click="selectProperties(prd, property)"
          href="javascript:;"
          v-for="property in prd.properties"
          :key="property.id"
          :class="{ active: property.selected }"
          >{{ property.name }}</a
        >
      </div>
    </div>
  </div>
</template>
<script>
import { inject } from 'vue'
export default {
  name: 'SubFilter',
  setup () {
    // 接受注入的数据
    const subCategoryData = inject('subCategoryData')

    // 接收注入的筛选条件的数据
    const filterParams = inject('filterParams')

    // 品牌点击事件高亮
    // 传入的参数，不局限于id
    // 可以根据遍历的内容传对象，传多个参
    const selectBrand = (brand) => {
      if (brand.seleced) return // 优化，选中当前的没变化，不执行

      // 记得加.value，父组件传过来的数据
      subCategoryData.value.brands.forEach((brand) => {
        brand.selected = false
      })
      brand.selected = true

      // 筛选条件的数据是响应式
      filterParams.value.brandId = brand.id
    }

    // 其它筛选条件点击事件高亮
    // 传入的参数，不局限于id
    // 可以根据遍历的内容传对象，传多个参
    const selectProperties = (prd, property) => {
      if (property.selected) return

      prd.properties.forEach((property) => {
        property.selected = false
      })
      property.selected = true

      // 一个条件下只能有一个具体值
      const index = filterParams.value.attrs.findIndex(item => item.groupName === prd.name)
      if (index > -1) {
        filterParams.value.attrs.splice(index, 1)
      }
      if (property.id !== null) {
        filterParams.value.attrs.push({
          groupName: prd.name, // 筛选条件名
          propertyName: property.name// 具体值
        })
      }
    }

    return { subCategoryData, selectBrand, selectProperties }
  }
}
</script>
<style scoped lang='less'>
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    padding: 10px 0;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        display: inline-block;
        margin-right: 36px;
        margin-bottom: 20px;
        transition: all 0.3s;
        border: 1px solid #eee;
        padding: 6px;
        &.active,
        &:hover {
          color: @xtxColor;
          border-color: @xtxColor;
        }
      }
    }
  }
}
</style>
